<template>
  <div id="main-container">
    <div id="main-body">
      <el-card class="box-card" v-loading="loading" :element-loading-text="loadingText">
        <div slot="header" class="clearfix">
          <strong> Physical Room Listing Edit |</strong>
          <el-button style="padding: 3px 10px;" type="text" plain  @click="doSynchro('create_listing')">新建房源</el-button>
          <el-button style="padding: 3px 10px;" type="text" plain  @click="doSynchro('update_listing')">更新基本信息</el-button>
          <el-button style="padding: 3px 10px;" type="text" plain  @click="doSynchro('update_listing_object')">更新全部信息</el-button>
          <el-button style="float: right; padding: 3px 0"  type="text" plain @click="goBack">Go Back</el-button>
          <el-button style="float: right; padding: 3px 20px;" type="text" plain  @click="doReset">Reset Form</el-button>

        </div>
        <el-form ref="formData" :rules="rules" :model="formData" label-width="115px" >
          <el-row type="flex" justify="space-around">
            <el-col :span="8">
              <el-form-item label="Physical Room" prop="physical_room_hook" >
                <el-input  placeholder="Please Enter Physical Room" v-model="formData.physical_room_hook"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Listing ID"  prop="listing_id">
                <el-input placeholder="Please Enter Listing ID" v-model="formData.listing_id"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Sync Status" prop="synchronization_category">
                <el-select placeholder="Please select A Sync Status" v-model="formData.synchronization_category">
                  <el-option label="Sync All" value="sync_all"></el-option>
                  <el-option label="Undecided" value="sync_undecided"></el-option>
                  <el-option label="Partial" value="sync_rates_and_availability"></el-option>
                  <el-option label="Stopped" value="stopped"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="space-around">
            <el-col :span="24">
              <el-form-item label="Name" prop="name">
                <el-input  placeholder="Please Enter Name" v-model="formData.name" style="width:75%; margin-right: 20px;"></el-input>
                <el-button type="primary" round @click="showDrawer(1)">Edit Listing Description</el-button>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>

          <el-row type="flex" justify="space-around">
            <el-col :span="12">
              <el-form-item label="Property Type Group" label-width="160px" prop="property_type_group">
                <el-select placeholder="Please select A Property Type Group" v-model="formData.property_type_group" style="width:80%;" @change="changeRoomTypeCagegory">
                  <el-option label="Apartment" value="apartments"></el-option>
                  <el-option label="BnB" value="bnb"></el-option>
                  <el-option label="Boutique Hotel" value="boutique_hotels_and_more"></el-option>
                  <el-option label="House" value="houses"></el-option>
                  <el-option label="Secondary Unit" value="secondary_units"></el-option>
                  <el-option label="Unique Home" value="unique_homes"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="Room Type Category" label-width="160px" prop="room_type_category">
                <el-select placeholder="Please select a Room Type Category" v-model="formData.room_type_category" style="width:80%;">
                  <el-option label="Private Room" value="private_room"></el-option>
                  <el-option label="Entire Home" value="entire_home"></el-option>
                  <el-option label="Shared Room" value="shared_room"></el-option>
                </el-select>
              </el-form-item>

            </el-col>
            <el-col :span="12">
              <el-form-item label="Property Type Category" label-width="175px" prop="property_type_category">
                <el-select placeholder="Please select a Property Type Category" v-model="formData.property_type_category" style="width:80%;">
                    <el-option v-for="item in roomTypeCagegoryList"  :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="BedRooms" prop="bedrooms">
<!--                <el-input  placeholder="Please Enter Bed Rooms" v-model="formData.bedrooms" style="width:85%;"></el-input>-->
                <el-input-number  placeholder="Please enter Bed Rooms" v-model="formData.bedrooms" :step="0.5" :min="0" :max="50"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" justify="space-around">
            <el-col :span="8">
              <el-form-item label="BathRooms" prop="bathrooms">
                <el-input-number  placeholder="Please enter Bath Rooms" v-model="formData.bathrooms" :step="0.5" :min="0" :max="50"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Beds" prop="beds">
<!--                <el-input placeholder="Please enter Beds" v-model="formData.beds"></el-input>-->
                <el-input-number  placeholder="Please enter Beds" v-model="formData.beds" :step="0.5" :min="0" :max="50"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Person Capacity"  label-width="175px" prop="person_capacity">
<!--                <el-input placeholder="Please enter Person Capacity" v-model="formData.person_capacity"></el-input>-->
                <el-input-number  placeholder="Please enter Person Capacity" v-model="formData.person_capacity" :step="0.5" :min="0" :max="50"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="20">
              <span style="position: absolute;top:12px;left:30px;color:red;">*</span>
              <el-form-item label="Amenities">
                <el-transfer  :titles="['Source', 'Target']"   filterable v-model="checkDatas" :data="amenitiesList"></el-transfer>
                <!--
                <el-cascader v-model="formData.amenity_categories"
                  :options="amenitiesList"
                  :props="{ multiple: true, checkStrictly: true }"
                   placeholder="Please select more Amenities"
                  clearable style="width:75%; margin-right: 20px;">
                </el-cascader>
                -->
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" round @click="showDrawer(2)">Manage Amenities</el-button>
            </el-col>
          </el-row>

          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="16">
              <el-form-item label="Apt #" prop="apt">
                <el-input  placeholder="Please enter Apt" v-model="formData.apt"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Country Code" prop="country_code">
                <el-select placeholder="Please select a Country Code" v-model="formData.country_code"  >
                  <el-option label="Japan" value="JP"></el-option>
                  <el-option label="China" value="CN"></el-option>
                  <el-option label="Thailand" value="TH"></el-option>
                  <el-option label="Malaysia" value="MY"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" justify="space-around">
            <el-col :span="24">
              <el-form-item label="Street" prop="street">
                <el-input  placeholder="Please enter Street" v-model="formData.street"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row type="flex" justify="space-around">
            <el-col :span="16">
              <el-form-item label="City" prop="city">
                <el-input  placeholder="Please enter City" v-model="formData.city"></el-input>
              </el-form-item>
              <el-form-item label="State/Province" prop="state">
                <el-input  placeholder="Please enter State/Province" v-model="formData.state"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="Zip Code" prop="zipcode">
                <el-input  placeholder="Please enter Zip Code" v-model="formData.zipcode"></el-input>
              </el-form-item>
              <el-form-item label="GPS" prop="lat">
                <el-input  placeholder="Please enter Lat" v-model="formData.lat" style="width:49%">
                  <template slot="prepend">Lat</template>
                </el-input>
                <el-input  placeholder="Please enter Lng" v-model="formData.lng" style="width:49%">
                  <template slot="prepend">Lng</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="11">
              <el-form-item label="Base Price" prop="listing_price">
                <el-input placeholder="Please enter Base Price" v-model="formData.listing_price" class="input-with-select">
                  <el-select v-model="formData.listing_currency" slot="prepend" placeholder="Listing Currency" style="width:175px;">
                    <el-option label="United States Dollar" value="USD"></el-option>
                    <el-option label="Chinese Yuan" value="CNY"></el-option>
                    <el-option label="Thai Baht" value="THB"></el-option>
                    <el-option label="Japanese Yen" value="JPY"></el-option>
                    <el-option label="Hong Kong Dollar" value="HKD"></el-option>
                    <el-option label="Malaysian Ringgit" value="MYR"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="13">
              <el-button type="primary" round @click="showDrawer(3)">Edit Pricing Settings</el-button>
              <el-button type="primary" round @click="showDrawer(4)">Edit Booking Settings</el-button>
              <el-button type="primary" round @click="showDrawer(5)">Edit Availability Rules</el-button>
            </el-col>
          </el-row>

          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="24">
              <el-form-item label="Check-in Option" label-width="125px"  prop="check_in_option_category">
                <el-radio-group v-model="formData.check_in_option_category">
                  <el-radio label="doorman_entry">Doorman Entry</el-radio>
                  <el-radio label="lockbox">Lock Box</el-radio>
                  <el-radio label="smartlock">Smart Lock</el-radio>
                  <el-radio label="keypad">Keypad</el-radio>
                  <el-radio label="host_checkin">Host Check-in</el-radio>
                  <el-radio label="other_checkin">Other</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="Check-in Instruction" label-width="150px"  prop="check_in_option_instruction">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 10}"
                  placeholder="Please enter Check-in Instruction"
                  v-model="formData.check_in_option_instruction">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="12">
              <el-form-item label="Bathroom Shared" label-width="160px" prop="bathroom_shared_with_category" >
                <el-switch v-model="formData.bathroom_shared" @change="switchChangeByCategory(1)">
                </el-switch>
                <el-select placeholder="Please select a Bathroom Shared With Category" v-model="formData.bathroom_shared_with_category" style="width:80%;" :disabled="!formData.bathroom_shared" >
                  <el-option label="With Host" value="host"></el-option>
                  <el-option label="With Family Friends or Roommates" value="family_friends_roommates"></el-option>
                  <el-option label="With Other Guests" value="other_guests"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Common Space Shared" label-width="175px" prop="common_spaces_shared_with_category">
                <el-switch v-model="formData.common_spaces_shared" @change="switchChangeByCategory(2)">
                </el-switch>
                <el-select placeholder="Please select a Common Spaces Shared With Category" v-model="formData.common_spaces_shared_with_category" style="width:80%;" :disabled="!formData.common_spaces_shared"  >
                  <el-option label="With Host" value="host"></el-option>
                  <el-option label="With Family Friends or Roommates" value="family_friends_roommates"></el-option>
                  <el-option label="With Other Guests" value="other_guests"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left"><el-button :type="unLockeFlag ?'primary' : 'danger'" :icon="unLockeFlag ?'el-icon-unlock' : 'el-icon-lock'" circle style="margin-right: 10px" @click="doLocker"></el-button>If you need to edit the following fields, click on the lock icon to unlock</el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="12">
              <el-form-item label="Total Inventory Count" label-width="175px" prop="total_inventory_count">
                <el-input  placeholder="Please enter Total Inventory Count" v-model="formData.total_inventory_count" :disabled="!unLockeFlag"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Property External Id" label-width="175px" prop="property_external_id">
                <el-input  placeholder="Please enter Property External Id" v-model="formData.property_external_id" :disabled="!unLockeFlag"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


          <el-divider></el-divider>
          <el-row type="flex" justify="space-around">
            <el-col :span="24">
              <el-form-item label="Automated Directions" label-width="175px"  prop="directions">
                <el-input
                  type="textarea"
                  :rows="10"
                  :autosize="{ minRows: 10, maxRows: 18}"
                  placeholder="Please enter Automated Directions"
                  v-model="formData.directions">
                </el-input>
              </el-form-item>

              <el-form-item style="text-align: center;">
                <el-button type="primary" @click="doSave('formData')">Save Changes</el-button>
                <el-button @click="doReset('formData')">Reset Form</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

    </div>

    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      direction="rtl" size="55%"
      :before-close="closeDrawer" style="overflow-y: scroll">
        <EditListingDescriptionForm v-show="actionType == 1" :pid.sync="formData.physical_room_hook" ref="editListingDescriptionForm"></EditListingDescriptionForm>
        <EditManageAmenitiesForm v-show="actionType == 2" :pid="formData.physical_room_hook" ref="editManageAmenitiesForm"></EditManageAmenitiesForm>
        <EditPricingSettingsForm v-show="actionType == 3" :pid="formData.physical_room_hook" :currency="formData.listing_currency" ref="editPricingSettingsForm"></EditPricingSettingsForm>
        <EditBookingSettingsForm v-show="actionType == 4" :pid="formData.physical_room_hook" ref="editBookingSettingsForm"></EditBookingSettingsForm>
        <EditAvailabilityRulesForm v-show="actionType == 5" :pid="formData.physical_room_hook" ref="editAvailabilityRulesForm"></EditAvailabilityRulesForm>
    </el-drawer>

  </div>
</template>

<!--
  房源上新界面（2）
  对应文档 FUNKEY FM3 前端（1）.docx 功能的：  房源上新界面
-->
<script>
    import Vue from 'vue'
    //import { Button, Select } from 'element-ui';
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    import EditListingDescriptionForm from '@/components/widgets/Room/EditListingDescriptionForm';
    import EditManageAmenitiesForm from '@/components/widgets/Room/EditManageAmenitiesForm';
    import EditPricingSettingsForm from '@/components/widgets/Room/EditPricingSettingsForm';
    import EditBookingSettingsForm from '@/components/widgets/Room/EditBookingSettingsForm';
    import EditAvailabilityRulesForm from '@/components/widgets/Room/EditAvailabilityRulesForm';
    import {addModel,searchModel,get,updateModel} from "@/api/model";
    import {submitAction} from "@/api/task";

    Vue.use(ElementUI);
    export default {
        name: "PhysicalRoomListingEdit",
        components: {EditListingDescriptionForm,EditManageAmenitiesForm,EditPricingSettingsForm,EditBookingSettingsForm,EditAvailabilityRulesForm},
        mixins: [],
        data() {
            return {
                loading: true,
                loadingText:'data loading ...',
                roomTypeCagegoryList:[],
                checkDatas: [],
                amenitiesList:[],
                unLockeFlag:false, // 锁标识
                actionType:0,
                drawerTitle: 'Info Edit',
                drawerVisible: false,
                physical_room_id:null,
                formActionType: null,
                formData: this.getInitFormData(),
                rules: this.getInitRules(),
                amenityCategoriesMsg:null //验证的错误提示 amenity_Categories
            }
        },
        created(){
        },
        mounted(){
          this.loadDatas();
        },
        watch:{
            "$route": "loadDatas"
        },
        methods: {
            getInitFormData(){
              return  {
                    physical_room_hook:null,//Hook   对应的PhysicalRoom外链
                    listing_id:null,//字符串   房源的Listing ID
                    synchronization_category:'sync_all',//字符串 房源的Listing ID
                    name:null,//字符串 房源的名字（标题），最长60字符。
                    property_type_group:null,//Enum字符串  房源类型的大类别。单选。
                    property_type_category:null,//Enum字符串
                    room_type_category:null,//Enum字符串
                    bedrooms:null,//整数  可以是任何大于等于0 小于50的整数。卧室的数量。
                    bathrooms:0,//浮点数    可以是任何大于等于0小于50的浮点数，以0.5为单位增减。例如允许1.0， 1.5， 5.5。但是不允许1.3， 2.7。卫生间的数量。
                    beds:null,//整数  床的数量
                    amenity_categories:null,  //[["essentials"], ["essentials"]]
                    amenity_categories_hook:null,//Hook  PhysicalRoomAmenityCategory的外链。只能选择存在的PhysicalRoomAmenityCategory。可多选。房源的设施。
                    permit_or_tax_id:null,//字符串 可选。 税务或者登记注册号。最长64字符。
                    apt:null,//字符串  可选。房源的房间号（同一个地址下有多个房源，例如公寓的情况）。不得含有特殊字符，只能是英文数字或者空格。最长32个字符。
                    street:null,//字符串   可选。房源的街道地址。最长120个字符。
                    city:null,//字符串 房源的城市。最长64个字符。
                    state:null,//字符串    可选。房源的省，或者州。最长64个字符。
                    zipcode:null,//字符串  可选。房源的邮政编码。最长20个字符。
                    country_code:null,//enum字符串 选一个。两位数的国家代码。
                    lat:null,//浮点数  纬度，-180.0到180.0
                    lng:null,//浮点数  经度，-180.0 到180.0
                    directions:null,//纯文本   可选，成单后的给客人看的指南。
                    person_capacity:null,//纯文本  可选，成单后的给客人看的指南。
                    listing_currency:null,//enum字符串 房源定价使用的货币
                    listing_price:null,//整数 有最高最低值的限制，建议写死一个粗略的汇率转换。最低USD 10，最高USD 25000。
                    //requested_approval_status_category:null,//字符串   不可编辑。新建时默认值是new。
                    check_in_option_category:null,//字符串enum 入住方式类型
                    check_in_option_instruction:null,//入住方式类型   入住方式的说明。最大1000字。
                    bathroom_shared:null,//布尔值  只有当room_type不是entire_home时才需要填写。
                    bathroom_shared_with_category:null,//字符串enum    只有当bathroom_shared为真时才需要填写
                    common_spaces_shared:null,//布尔值 只有当room_type不是entire_home时才需要填写。
                    common_spaces_shared_with_category:null,//字符串enum   只有当common_spaces_shared为真时才需要填写。和bathroom_shared_with_category的选项相同。
                    total_inventory_count:null,//整数 0到500间的整数。默认是1。同类型可售卖房源总数。
                    property_external_id:null//字符串  最长64字符。房子所在小区的名字。可以自己起。但是同样小区的房子id应该填一样的。
                };
            },
            getInitRules(){
              const _this = this;
              const custRulesCfg = this.getCustRulesConfig();
              const bedsRoomsValid = custRulesCfg.intValid('BedRooms',0,50);
              const bathRoomsValid = custRulesCfg.floatValid('BathRooms',0,50);

              const bedsValid = custRulesCfg.intValid('Beds',1,50);
              const personCapacityValid = custRulesCfg.intValid('Person Capacity',1,100);
              const latValid = custRulesCfg.floatValid('GPS Lat',-180,190);
              const lngValid = custRulesCfg.floatValid('GPS Lng',-180,190);
              const listingPriceValid = custRulesCfg.floatValid('Base Price',0,100000,(rule, value, callback) => {
                if(!_this.formData.listing_currency){
                    callback(new Error('Please select a Listing Currency'));
                }else{
                    callback();
                }
              });
              const bathroomSharedValid = (rule, value, callback) => {
                  if(_this.formData.bathroom_shared && !value){
                      callback(new Error('Please select a Bathroom Shared With Category'));
                  }else{
                      callback();
                  }
              };
              const commonSpacesSharedValid = (rule, value, callback) => {
                  if(_this.formData.common_spaces_shared && !value){
                      callback(new Error('Please select a Common Spaces Shared With Category'));
                  }else{
                      callback();
                  }
                };
              const totalInventoryCountValid = (rule, value, callback) => {
                  if(_this.unLockeFlag){
                      const label = 'Total Inventory Count';
                      const min = 1;
                      const max = 500;
                      if (!value) {
                          callback(new Error('Please Enter '+label));
                      }
                      try{
                          value = parseInt(value);
                      }catch (e) {
                          callback(new Error(label+' Must be an integer value'));
                      }

                      if (!Number.isInteger(value)) {
                          callback(new Error(label+' Must be an integer value'));
                      }

                      if(value < min || value > max){
                          callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                      }else{
                          callback();
                      }

                  }else{
                      _this.formData.total_inventory_count = null;
                      callback();
                  }
              };

              const propertyExternalIdValid = (rule, value, callback) => {
                  if(_this.unLockeFlag){
                     if(!value){
                         callback(new Error('Please Enter Property External Id'));
                     }else{
                         if(value.length < 1 || value.length > 64){
                             callback(new Error('1 to 64 characters in length'));
                         }else{
                             callback();
                         }
                     }
                  }else{
                      _this.formData.property_external_id = null;
                      callback();
                  }
              };

              const amenityCategoriesValid =  (rule, value, callback) => {
                  if(_this.amenityCategoriesMsg){
                      callback(new Error(_this.amenityCategoriesMsg));
                  }else{
                      callback();
                  }
              };

              return    {
                physical_room_hook: [
                  { required: true, message: 'Please Enter Physical Room', trigger: 'blur' },
                  { min: 1, max: 30, message: '1 to 30 characters in length', trigger: 'blur' }
                ],
                listing_id: [
                  { required: true, message: 'Please Enter Listing ID', trigger: 'blur' },
                  { min: 1, max: 30, message: '1 to 30 characters in length', trigger: 'blur' }
                ],
                synchronization_category: [
                  { required: true, message: 'Please select A Sync Status', trigger: 'change' }
                ],
                name: [
                  { required: true, message: 'Please Enter Name', trigger: 'blur' },
                  { min: 2, max: 60, message: '2 to 60 characters in length', trigger: 'blur' }
                ],
                property_type_group: [
                  { required: true, message: 'Please select A Property Type Group', trigger: 'change' }
                ],
                room_type_category: [
                  { required: true, message: 'Please select a Room Type Category', trigger: 'change' }
                ],
                property_type_category: [
                  { required: true, message: 'Please select a Property Type Category', trigger: 'change' }
                ],
                bedrooms: [
                  { required: true,validator:bedsRoomsValid,  trigger: 'blur' }
                ],
                bathrooms: [
                  { required: true,validator: bathRoomsValid,  trigger: 'blur' }
                ],
                beds: [
                  { required: true,validator: bedsValid,  trigger: 'blur' }
                ],
                person_capacity: [
                  { required: true,validator: personCapacityValid,  trigger: 'blur' }
                ],
                  // amenity_categories: [
                  //     { validator: amenityCategoriesValid}
                  // ],
                  /*
                amenity_categories: [
                  { type: 'array', required: true, message: 'Please select more Amenities', trigger: 'change' }
                ],
                */
                country_code: [
                  { required: true, message: 'Please select a Country Code', trigger: 'change' }
                ],
                street: [
                  { required: true, message: 'Please Enter Street', trigger: 'blur' },
                  { min: 2, max: 120, message: '2 to 120 characters in length', trigger: 'blur' }
                ],
                city: [
                  { required: true, message: 'Please Enter City', trigger: 'blur' },
                  { min: 2, max: 64, message: '2 to 64 characters in length', trigger: 'blur' }
                ],
                zipcode: [
                  { required: true, message: 'Please Enter Zip Code', trigger: 'blur' },
                  { min: 2, max: 20, message: '2 to 20 characters in length', trigger: 'blur' }
                ],
                state: [
                  { required: true, message: 'Please Enter State/Province', trigger: 'blur' },
                  { min: 2, max: 64, message: '2 to 64 characters in length', trigger: 'blur' }
                ],
                lat: [
                  { required: true, validator: latValid,  trigger: 'blur' },
                ],
                lng: [
                  { required: true, validator: lngValid,  trigger: 'blur' },
                ],
                listing_price:[
                  { required: true,validator: listingPriceValid,  trigger: 'blur' }
                ],
                check_in_option_instruction: [
                  { required: true, message: 'Please Enter Check-in Instruction', trigger: 'blur' },
                  { min: 2, max: 1000, message: '2 to 1000 characters in length', trigger: 'blur' }
                ],
                bathroom_shared_with_category:[
                    { validator: bathroomSharedValid,  trigger: 'change' }
                ],
                common_spaces_shared_with_category:[
                    { validator: commonSpacesSharedValid,  trigger: 'change' }
                ],
                total_inventory_count:[
                    { validator: totalInventoryCountValid,  trigger: 'blur' }
                ],
                property_external_id:[
                    { validator: propertyExternalIdValid,  trigger: 'blur' }
                ],
                directions: [
                  { required: true, message: 'Please Enter Automated Directions', trigger: 'blur' },
                  { min: 2, max: 1000, message: '2 to 1000 characters in length', trigger: 'blur' }
                ],
              };
            },
            getCustRulesConfig(){
                return {
                  intValid: function(label, min, max){
                    const intValidFun = (rule, value, callback) => {
                      if (!value) {
                         callback(new Error('Please Enter '+label));
                      }
                      try{
                        value = parseInt(value);
                      }catch (e) {
                         callback(new Error(label+' Must be an integer value'));
                      }

                      if (!Number.isInteger(value)) {
                         callback(new Error(label+' Must be an integer value'));
                      }
                      if(min != null && max != null){
                        if(value < min || value > max){
                          callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                        }else{
                          callback();
                        }
                      }
                      if(min != null && max == null){
                        if (min && min > value) {
                          callback(new Error(label+' Must be greater than or equal to '+min));
                        } else {
                          callback();
                        }
                      }

                      if(max != null && min == null){
                        if (max && value > max) {
                           callback(new Error(label+' Must be less than or equal to '+max));
                        } else {
                          callback();
                        }
                      }
                    };
                    return intValidFun;
                  },
                  floatValid: function(label, min, max,custCb){
                    const intValidFun = (rule, value, callback) => {
                      if (!value) {
                        callback(new Error('Please Enter '+label));
                      }
                      try{
                        value = parseFloat(value);
                      }catch (e) {
                        callback(new Error(label+' Must be an float value'));
                      }

                      if(min != null && max != null){
                        if(value < min || value > max){
                          callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                        }else{
                            console.log("custCb...");
                            console.log(custCb);
                            if(custCb){
                                custCb(rule, value, callback);
                            }else{
                                callback();
                            }
                        }
                      }
                      if(min != null && max == null){
                        if (min && min > value) {
                          callback(new Error(label+' Must be greater than or equal to '+min));
                        } else {
                            callback();
                        }
                      }

                      if(max != null && min == null){
                        if (max && value > max) {
                          callback(new Error(label+' Must be less than or equal to '+max));
                        } else {
                          callback();
                        }
                      }

                    };
                    return intValidFun;
                  },
                };
            },
            switchChangeByCategory(action){
                switch (action) {
                    case 1 :{
                        console.log(this.formData.bathroom_shared);
                       if(!this.formData.bathroom_shared) this.formData.bathroom_shared_with_category = null;
                        break;
                    }case 2 :{
                        console.log(this.formData.common_spaces_shared);
                        if(!this.formData.common_spaces_shared) this.formData.common_spaces_shared_with_category = null;
                        break;
                    }

                }
            },
            doLocker(){
                this.unLockeFlag = !this.unLockeFlag;
            },
            changeRoomTypeCagegory(val){
                let _roomTypeCagegoryList = [];
                switch (val) {
                    case 'apartments':{
                        _roomTypeCagegoryList = [
                            {label:'Apartment', value:'apartment'},
                            {label:'Condominium', value:'condominium'},
                            {label:'Casa Particular (Cuba)', value:'casa_particular'},
                            {label:'Loft', value:'loft'},
                            {label:'Serviced Apartment', value:'serviced_apartment'}
                        ];
                        break;
                    } case 'bnb':{
                        _roomTypeCagegoryList = [
                            {label:'BNB', value:'bnb'},
                            {label:'Casa Particular (Cuba)', value:'casa_particular'},
                            {label:'Farm Stay', value:'farm_stay'},
                            {label:'Minsu (Taiwan)', value:'minsu'},
                            {label:'Nature Lodge', value:'lodge'},
                            {label:'Ryokan (Japan)', value:'ryokan'}
                        ];
                        break;
                    }case 'boutique_hotels_and_more':{
                        _roomTypeCagegoryList = [
                            {label:'Boutique Hotel', value:'boutique_hotel'},
                            {label:'Aparthotel', value:'aparthotel'},
                            {label:'Heritage Hotel (India)', value:'heritage_hotel'},
                            {label:'Hostel', value:'hostel'},
                            {label:'Hotel', value:'hotel'},
                            {label:'Lodge', value:'lodge'},
                            {label:'Resort', value:'resort'},
                            {label:'Serviced Apartment', value:'serviced_apartment'}
                        ];
                        break;
                    }case 'houses':{
                        _roomTypeCagegoryList = [
                            {label:'House', value:'house'},
                            {label:'Bungalow', value:'bungalow'},
                            {label:'Cabin', value:'cabin'},
                            {label:'Casa Particular (Cuba)', value:'casa_particular'},
                            {label:'Chalet', value:'chalet'},
                            {label:'Cottage', value:'cottage'},
                            {label:'Cycladic House', value:'cycladic_house'},
                            {label:'Dammuso', value:'dammuso'},
                            {label:'Dome House', value:'dome_house'},
                            {label:'Earth House', value:'earthhouse'},
                            {label:'Farm Stay', value:'farm_stay'},
                            {label:'Houseboat', value:'houseboat'},
                            {label:'Hut', value:'hut'},
                            {label:'Lighthouse', value:'lighthouse'},
                            {label:'Pension', value:'pension'},
                            {label:'Sheperd\'s Hut (UK)', value:'sheperds_hut'},
                            {label:'Tiny House', value:'tiny_house'},
                            {label:'Townhouse', value:'townhouse'},
                            {label:'Trullo', value:'trullo'},
                            {label:'Villa', value:'villa'}
                        ];
                        break;
                    }case 'secondary_units':{
                        _roomTypeCagegoryList = [
                            {label:'Guesthouse', value:'guesthouse'},
                            {label:'Guest Suite', value:'guest_suite'},
                            {label:'Farm Stay', value:'farm_stay'}
                        ];
                        break;
                    }case 'unique_homes':{
                        _roomTypeCagegoryList = [
                            {label:'Barn', value:'barn'},
                            {label:'Boat', value:'boat'},
                            {label:'Bus', value:'bus'},
                            {label:'RV', value:'rv'},
                            {label:'Campsite', value:'campsite'},
                            {label:'Castle', value:'castle'},
                            {label:'Cave', value:'cave'},
                            {label:'Dome House', value:'dome_house'},
                            {label:'Earth House', value:'earthhouse'},
                            {label:'Farm Stay', value:'farm_stay'},
                            {label:'Houseboat', value:'houseboat'},
                            {label:'Hut', value:'hut'},
                            {label:'Igloo', value:'igloo'},
                            {label:'Island', value:'island'},
                            {label:'Lighthouse', value:'lighthouse'},
                            {label:'Pension', value:'pension'},
                            {label:'Plane', value:'plane'},
                            {label:'Sheperd\'s Hut (UK)', value:'sheperds_hut'},
                            {label:'Tent', value:'tent'},
                            {label:'Tiny House', value:'tiny_house'},
                            {label:'Tipi', value:'tipi'},
                            {label:'Train', value:'train'},
                            {label:'Tree House', value:'treehouse'},
                            {label:'Windmill', value:'windmill'},
                            {label:'Yurt', value:'yurt'}
                        ];
                        break;
                    }default:{
                        console.error("Property Type Group 枚举对应的 Property Type Category 不存在！");
                    }
                }
                this.roomTypeCagegoryList = _roomTypeCagegoryList;
            },
            /**
             * 返回
             */
            goBack(){
                this.$router.go(-1);//返回上一层
            },
           loadDatas(){
             console.log("======= loadDatas ========");
             const _this = this;
             const pars = this.$route.params;
             console.log(pars);
             this.physical_room_id = null;
             const {actionType,physical_room_id} = pars;
             this.formActionType = actionType;
             this.doReset('formData');
             if(actionType == 'EDIT'){
                 this.physical_room_id = physical_room_id;
                 console.log("_physical_room_id="+physical_room_id);
                 this.loadAmenityCategories(() =>{
                     _this.loadPhysicalRoomListing(physical_room_id);
                 });
             }else{ // ADD
                 this.loadAmenityCategories(() =>{
                     _this.loading = false;
                 });
             }
           },
          loadPhysicalRoomListing(_physical_room_id){
              this.loading = true;
              let _this = this;
              get('PhysicalRoomListing', _physical_room_id).then(res => {
                  console.log("====== loadPhysicalRoomListing =====");
                  console.log(res);
                  _this.loading = false;
                  if(!res || !res.data){
                      _this.formData =_this.getInitFormData();
                      return;
                  }
                  const list = res.data.list;
                  if(!list || list.length == 0){
                      console.error("找不到ID="+_physical_room_id+" 的 PhysicalRoomList Data!");
                      return;
                  }
                  const data = list[0];

                  _this.renderPhysicalRoomListingData(data);
              }).catch(reason => {
                  _this.loading = false;
                  console.error(reason);
              });
          },
          renderPhysicalRoomListingData(data){
                console.log("renderPhysicalRoomListingData");
              if(data.amenity_categories_hook){
                  const amenity_categoriesArr = data.amenity_categories_hook.split(";");
                  console.log(amenity_categoriesArr);
                  data.amenity_categories = amenity_categoriesArr;

              }
              if(data.total_inventory_count || (data.total_inventory_count === 0 || data.total_inventory_count === '0') || data.property_external_id){
                  this.unLockeFlag = true;
              }else{
                  this.unLockeFlag = false;
              }
              this.formData = data;
              this.setTransferChecked();
          },
          loadAmenityCategories(callBack){
              let _this = this;
              searchModel('PhysicalRoomAmenityCategory', {
                search_keys:{}
              }).then(res => {
                if(callBack) callBack();
                if(!res || !res.data){
                    _this.amenitiesList = [];
                    return;
                }
                const list = res.data.list;
                if(!list || list.length == 0){
                  _this.amenitiesList = [];
                  return;
                }
                _this.transferAmenitiesList(list);
              }).catch(reason => {
                  _this.loading = false;
                console.error(reason);
              });
          },
            /**
             *  当 manage Amenities 表单数据有增加时会调用此方法重新加载数据
             * */
          transferAmenitiesList(list){
              this.amenitiesList = list.map( item => {
                  return {key: item.name, label: item.name};
                  //return {label: item.name, value: item.name};
              });
          },

          setTransferChecked(){
              const categories = this.formData.amenity_categories;
              console.log("setTransferChecked...");
              console.log(categories);
              if(!categories || categories.length == 0){
                  return;
              }
              const _this = this;
              this.amenitiesList.forEach(item => {
                  const _rule_name = item.label;
                  const _id = item.key;
                  for(let i=0, count=categories.length; i<count; i++){
                      if(categories[i] == _rule_name){
                          _this.checkDatas.push(_id);
                          break;
                      }
                  }
              });
              console.log(_this.checkDatas);
          },
          doCustValid(){
            const _this = this;
            const amenity_categories = this.checkDatas;
            if(!amenity_categories || amenity_categories.length == 0){
                _this.$message.error("Please select more Amenities");
                return false;
            }
            const _bathRooms = this.formData.bathrooms;
            let result = _bathRooms/0.5;
            result+="";
            if(result.indexOf(".") != -1){
                result = result.substring(result.indexOf(".")+1);
                result = parseInt(result);
                if(result > 0){
                    _this.$message.error('BathRooms  Must be a multiple of 5 ');
                    return false;
                }
            }
            return true;
          },
            /**
             * 保存数据
             */
            doSave(formName){
              console.log(formName+" doSave to do ...");
              const _this = this;
              let _formData = this.formData;
              const amenity_categories = this.checkDatas;
              console.log("amenity_categories="+amenity_categories);
              if(amenity_categories && amenity_categories.length > 0){
                let  amenity_categories_val = amenity_categories.join(";");
                _formData.amenity_categories_hook = amenity_categories_val;
                delete _formData['amenity_categories'];
              }

              for(var key in _formData){
                  const val = _formData[key];
                  if(!val && (val !== 0 || val !== '0')){
                      delete _formData[key];
                  }
              }

              const jsonStr =  JSON.stringify(_formData);
             // console.log(jsonStr);
              this.$refs[formName].validate((valid) => {
                if(!this.doCustValid()) return;
                if (valid) {
                    _this.loading = true;
                    if(_this.physical_room_id){
                        updateModel('PhysicalRoomListing', _this.physical_room_id, _formData).then(res => {
                            _this.loading = false;
                           // console.log(res);
                           // _this.doReset('formName');
                            _this.goBack();
                        }).catch(reason => {
                            _this.loading = false;
                            console.log("doSave Failure...");
                            console.log(reason);
                            _this.$message.error('Please Check Input Form Data Has Errors!');
                        });
                    }else{
                        addModel('PhysicalRoomListing', jsonStr).then(res => {
                            _this.loading = false;
                            //console.log(res);
                          //  _this.doReset('formName');
                            _this.goBack();
                        }).catch(reason => {
                            _this.loading = false;
                            console.log("doSave Failure...");
                            console.log(reason);
                            _this.$message.error('Please Check Input Form Data Has Errors!');
                        });
                    }
                } else {
                  console.log('error submit!!');
                    _this.$message.error('Please Check Input Form Data Has Errors!');
                  return false;
                }
              });
            },

            /**
             * 重置表单
             */
            doReset(formName){
              console.log("doReset to do ...");
              this.checkDatas = [];
              this.formData = this.getInitFormData();
              this.$refs[formName].resetFields();
              //this.formData = this.getInitFormData();
            },
            /***---------- 抽屉 子业务表单部份 CODE START --------***/
            closeDrawer(){
                this.drawerVisible = false;
            },
            showDrawer(actionType){
                const _this = this;
                this.actionType = actionType;
                let parValidFlag = 1;
                let _drawerTitle = 'Info Edit';
                let refEle = null;
                switch (actionType) {
                    case 1: {//Edit Listing Description Button Action
                        _drawerTitle = 'Edit Listing Description';
                        parValidFlag = 1;
                        refEle = "editListingDescriptionForm";
                        break;
                    }case 2: {//Edit Manage Amenities Button Action
                        _drawerTitle = 'Edit Manage Amenities';
                        parValidFlag = 1;
                        refEle = "editManageAmenitiesForm";
                        break;
                    }case 3: {//Edit Pricing Settings Button Action
                        _drawerTitle = 'Edit Pricing Settings';
                        parValidFlag = 2;
                        refEle = "editPricingSettingsForm";
                        break;
                    }case 4: {//Edit Booking Settings Button Action
                        _drawerTitle = 'Edit Booking Settings';
                        parValidFlag = 1;
                        refEle = "editBookingSettingsForm";
                        break;
                    }case 5: {//Edit Availability Rules Button Action
                        _drawerTitle = 'Edit Availability Rules';
                        parValidFlag = 1;
                        refEle = "editAvailabilityRulesForm";
                        break;
                    }
                }
                if(parValidFlag == 1 && !this.formData.physical_room_hook){//
                    this.$message.error('Please Enter Physical Room!');
                    return;
                }else if(parValidFlag == 2 && (!this.formData.physical_room_hook || !this.formData.listing_currency)){
                    this.$message.error('Please Enter Physical Room And Select A Listing Currency!');
                    return;
                }
                this.drawerTitle = _drawerTitle;
                this.drawerVisible = true;

                if(refEle){
                    window.setTimeout(() => {
                        console.log( _this.$refs.editListingDescriptionForm);
                       if(_this.$refs[refEle].refresh) _this.$refs[refEle].refresh(this);
                    },150);
                }
            },
            /**
             * 抽屉 子业务表单部份
             */
            closeDrawer(){
                this.drawerTitle = 'Info Edit';
                this.drawerVisible = false;
            },
            /***---------- 抽屉 子业务表单部份 CODE END --------***/
            /**
             * ActionTask ABNB API 同步
             */
            doSynchro(actionName){
                const _this = this;

                if(!this.physical_room_id){
                    _this.$message.error('PhysicalRoomListing id is null,Please Check Data...!');
                    return;
                }
                this.loadingText = "Calling API: "+actionName+" ...";
                this.loading = true;

                submitAction("PhysicalRoomListing", this.physical_room_id,actionName).then(res => {
                    this.loading = false;
                    _this.$notify({
                        title: 'Success',
                        message: 'ListingId:'+ this.physical_room_id+' call API:'+actionName+' succeeded !',
                        type: 'success'
                    });

                }).catch(reason => {
                    _this.loading = false;
                    console.log("deleteModel Failure...");
                    console.error(reason);
                    _this.$notify.error({
                        title: 'Error',
                        message: 'API:'+actionName+'  call error !'
                    });
                    //_this.$message.error('Please Check Input Form Data Has Errors!');
                });

            }
        }
    }

</script>


<style lang="less" scoped>
  body{
    overflow: hidden;
  }
  #main-container {
    padding: 1rem;
    border: 1px solid #ebeef5;
    background-color: white;
  }

  #main-body{
    width: 1130px;
    text-align: left;
    margin:0 auto;
    /*border: 1px solid #00ff00;*/
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 1124px;
  }

  .el-select .el-input {
    width: 130px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
